package org.wedding.center.util;
import java.security.SecureRandom;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 邀请码生成工具类
 * @author sky
 * @since 2025-04-29 17:31:49
 */
public class InvitationCodeGenerator {
    // 字符库（共62个字符）
    private static final String[] CHARACTERS = {
            "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t",
            "u", "v", "w", "x", "y", "z",
            "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
            "U", "V", "W", "X", "Y", "Z"
    };

    // 使用线程安全的Set存储已生成的邀请码
    private static final Set<String> existingCodes = Collections.newSetFromMap(new ConcurrentHashMap<>());
    private static final SecureRandom random = new SecureRandom();

    // 生成唯一邀请码
    public static String generateCode() {
        StringBuilder code = new StringBuilder(8);
        do {
            code.setLength(0); // 清空StringBuilder
            for (int i = 0; i < 8; i++) {
                int index = random.nextInt(CHARACTERS.length);
                code.append(CHARACTERS[index]);
            }
        } while (!existingCodes.add(code.toString())); // 检查唯一性

        return code.toString();
    }

//    public static void main(String[] args) {
//        Set<String> invitationCodes = new HashSet<>();
//        invitationCodes.add("OV0OdSuF");
//        invitationCodes.add("27eKQ0BZ");
//        invitationCodes.add("RU0j6szg");
//        invitationCodes.add("me5fnsjK");
//        String invitationCode = InvitationCodeGenerator.generateCodeData(invitationCodes);
//        System.out.println(invitationCode);
//    }
    // 生成唯一邀请码 通过传入已存在的邀请码集合进行校验
    public static String generateCodeData(Set<String> existingCodes) {
        StringBuilder code = new StringBuilder(8);
        do {
            code.setLength(0); // 清空StringBuilder
            for (int i = 0; i < 8; i++) {
                int index = random.nextInt(CHARACTERS.length);
                code.append(CHARACTERS[index]);
            }
        } while (!existingCodes.add(code.toString())); // 检查唯一性

        return code.toString();
    }

    // 验证码是否有效
    public static boolean isValidCode(String code) {
        return code != null
                && code.length() == 8
                && existingCodes.contains(code);
    }

    // 重置生成记录
    public static void resetGenerator() {
        existingCodes.clear();
    }
}
